import React from "react";

import { Route, NavLink, Switch } from "react-router-dom";

import { Tabs } from "antd";
import { Button } from "antd";

import Store from "./Store";
import Connect from "./Connect";
import Antd from "./Antd";
import ConnectedRouter from "./ConnectedRouter";
import Middleware from "./Middleware";
import Persist from "./Persist";
import Less from "./Less";
import CSS from "./CSS";
import loadable from "@loadable/component";

const base = "/test";
const _import_path = base + "/import";

class Test extends React.Component {
  constructor(props) {
    super(props);
    console.log("Test", props);
    this.state = {
      route: null,
    };
    this.link_list = [
      "store",
      "connect",
      "antd",
      "connectedRouter",
      "middleware",
      "persist",
      "less",
      "css"
    ];
    this.component_list = [
      Store,
      Connect,
      Antd,
      ConnectedRouter,
      Middleware,
      Persist,
      Less,
      CSS,
    ];
  }

  componentDidMount() {
    this.props.location.pathname === _import_path && this.addComponent();
  }

  // 原始不用loadable的包做法
  // addComponent = async () => {
  //   try {
  //     let data = await import(
  //       /* webpackChunkName: "import" */ "./Import/index"
  //     );
  //     this.setState({
  //       route: (
  //         <>
  //           <Route path={_import_path} component={data.default}></Route>
  //         </>
  //       ),
  //     });
  //     this.props.history.push(_import_path);
  //   } catch (e) {
  //     console.log(e);
  //   }
  // };

  addComponent=()=>{
    const Import=loadable(()=>import(/* webpackChunkName: "import" */ "./Import/"));
    this.setState({
      route:(
        <>
            <Route path={_import_path} component={Import}></Route>
        </>
      )
    })
    this.props.history.push(_import_path);
  }

  render() {
    return (
      <>
        {this.link_list.map((item, index) => (
          <NavLink to={`${base}/${item}`} key={index}>
            {item} |
          </NavLink>
        ))}

        <Button type="primary" onClick={this.addComponent}>
          懒加载
        </Button>

        <hr />
        <Switch>
          {this.component_list.map((item, index) => (
            <Route
              path={`${base}/${this.link_list[index]}`}
              component={item}
              key={index}
            ></Route>
          ))}
          {this.state.route}
        </Switch>
      </>
    );
  }
}

export default Test;
